package com.aurora.gulimall.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.aurora.common.utils.HttpUtils;
import com.aurora.common.utils.R;
import com.aurora.common.vo.MemberResponseVo;
import com.aurora.gulimall.auth.feign.MemberFeignService;
import com.aurora.gulimall.auth.vo.SocialUser;
import com.aurora.gulimall.auth.vo.SocialUserInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * 处理社交登录请求
 */
@Controller
@Slf4j
public class OAuth2Controller {
    @Autowired
    private MemberFeignService memberFeignService;
    @GetMapping("/oauth2.0/gitee/success")
    public String gitee(@RequestParam("code") String code, HttpSession session) throws Exception {
        Map<String, String> headers = new HashMap<String, String>();
        Map<String, String> querys = new HashMap<String, String>();
        //1、根据code换取access_token
        Map<String,String> map  = new HashMap<>();
        map.put("grant_type","authorization_code");
        map.put("code",code);
        map.put("client_id","f21ce4a1894b1ebde24c695dc17fa3db59f4feeea94211b0cb052b566c78b920");
        map.put("client_secret","169f9fcc35a6d199fed794ac2435acd80853b1bd2eefe4a840a35a6066d57f2d");
        map.put("redirect_uri","http://auth.gulimall.com/oauth2.0/gitee/success");
        HttpResponse response= HttpUtils.doPost("https://gitee.com", "/oauth/token", "post", headers, querys, map);
        if(response.getStatusLine().getStatusCode() == 200){
            //获取到了accessToken
            String respString = EntityUtils.toString(response.getEntity());
            SocialUser socialUser = JSON.parseObject(respString, SocialUser.class);
            String accessToken = socialUser.getAccess_token();
            Map<String,String> map2 = new HashMap<>();
            map2.put("access_token",accessToken);
            HttpResponse response1 = HttpUtils.doGet("https://gitee.com", "/api/v5/user", "get", headers, map2);
            if(response1.getStatusLine().getStatusCode() == 200){
                String s = EntityUtils.toString(response1.getEntity());
                SocialUserInfo socialUserInfo = JSON.parseObject(s, SocialUserInfo.class);
                socialUser.setSocialUserInfo(socialUserInfo);
                R r = memberFeignService.socialLogin(socialUser);
                if(r.getCode() == 0){
                    //2、登录成功，调回首页
                    MemberResponseVo data = r.getData(new TypeReference<MemberResponseVo>() {
                    });
                    //TODO 1、默认发的令牌。session=xxx.作用域为当前域(需解决子域session共享问题)
                    //TODO 使用json的序列化方式来序列化对象存redis（
                    session.setAttribute("loginUser",data);
                    //1、第一次使用session；命令浏览器保存jsessionid这个cookie
                    //为了子域之间能共享：发卡时指定域名为父域名，即使是子域名系统发的卡，也能让父域直接使用
                    //httpservletresponse 可以修改session的域，但是session域是由tomcat第一次使用时指定的，自己书写较麻烦
//                    httpServletResponse.addCookie();
//                    new Cookie("jsessionid","").setDomain("")

                    log.info("登录成功，用户信息"+data);
                    return "redirect:http://gulimall.com";
                }else {
                    return "redirect:http://auth.gulimall.com/login.html";
                }
            }
            return "error";
        }else{
            return "redirect:http://auth.gulimall.com/login.html";
        }



    }

}
